package com.example.shw

import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.StringBuilder
import java.net.URL

class AsyncTaskActivity : AppCompatActivity() {
    private lateinit var show: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_asynctask)
        show = findViewById(R.id.show)
    }

    fun download(v: View) {
        val task = DownTask(this,findViewById(R.id.progress))
        task.execute(URL("http://www.keeplovepet.cn/"))
    }

    internal inner class DownTask(var mContext: Context, private var progressBar: ProgressBar) :
        AsyncTask<URL, Int, String>() {
        private var hasRead = 0
        override fun doInBackground(vararg params: URL): String? {
            val sb = StringBuilder()
            val conn = params[0].openConnection()
            val br = BufferedReader(InputStreamReader(conn.getInputStream(),"utf-8"))
            var line : String ?= br.readLine()
            while (line != null){
                sb.append(line + "\n")
                hasRead++
                publishProgress(hasRead)
                line = br.readLine()
            }
            return sb.toString()
        }

        override fun onPostExecute(result: String?) {
            show.text = result
            progressBar.visibility = View.INVISIBLE
        }

        override fun onPreExecute() {
            progressBar.visibility = View.VISIBLE

            progressBar.progress = 0

            progressBar.max = 120
        }

        override fun onProgressUpdate(vararg values: Int?) {
            show.text = "已经读取了【" + values[0] + "】行！"
            progressBar.progress = values[0]!!
        }
    }
}